var editRowsNumber,_datasDatagrid,selectForm,createDate1,createDate2,selectUsername,selectNickname,selectEmail,selectPhone,selectStatus;
var parentCenterTabs,dialogWeixinMsg,formWeixinMsg,id,status,title,description,logo,sessionID,picUrl,url,author,digest,content,content_source_url,show_cover_pic,thumb_media_id;

function addRow() {
	if (editRowsNumber != -1) {
		_datasDatagrid.datagrid('endEdit', editRowsNumber);
	} else {
		id.val(0);
		title.val('');
		description.val('');
		picUrl.val('');
		url.val('');
		author.val('');
		digest.val('');
		content.val('');
		content_source_url.val('');
		show_cover_pic.combobox('setValue',1);
		dialogWeixinMsg.dialog({title:'添加回复消息',iconCls:'icon-add',buttons:[{text:'添加',handler:dialogHandler}]});
		dialogWeixinMsg.dialog('open');
	}
}

function deleteRow() {
	var rows = _datasDatagrid.datagrid('getSelections');
	if (rows.length > 0) {
		$.messager.confirm('请确认', '您确实要删除当前所有选择的记录吗？', function(b){
			if (b) {
				var ids = [];
				for ( var i = 0; i < rows.length; i++) {
					ids.push(rows[i].id);
				}
				$.post(sy.bp()+"/admin/weixin/imageTextMsg/deletes", {ids:ids.join(",")}, function(data) {
					if (data.result==1) {
						$.messager.show({msg:data.msg,title:'系统提示'});
						editRowsNumber = -1;
						_datasDatagrid.datagrid('unselectAll');
						_datasDatagrid.datagrid('reload');
					} else {
						$.messager.alert('警告', data.msg, 'warning');
					}
				}, "json");
			}
		});
	} else {
		$.messager.alert('提示', '请选择要删除的记录', 'error');
	}
}

function updateRow() {
	var rows = _datasDatagrid.datagrid('getSelections');
	switch (rows.length) {
	case 0:
		$.messager.alert('提示', '请选择要修改的记录', 'warning');
		break;
	case 1:
		if (editRowsNumber != -1) {
			_datasDatagrid.datagrid('endEdit', editRowsNumber);
		} else {
			var rowData = rows[0];
			id.val(rowData.id);
			status.combobox('setValue',rowData.status);
			title.val(rowData.title);
			description.val(rowData.description);
			picUrl.val(rowData.picUrl);
			url.val(rowData.url);
			author.val(rowData.author);
			digest.val(rowData.digest);
			content.val(rowData.content);
			content_source_url.val(rowData.content_source_url);
			show_cover_pic.combobox('getValue', rowData.show_cover_pic);
			thumb_media_id.combogrid('getValue', rowData.thumb_media_id);
			dialogWeixinMsg.dialog({title:'更新回复消息',iconCls:'icon-add',buttons:[{text:'更新',handler:dialogHandler}]});
			dialogWeixinMsg.dialog('open');
		}
		break;
	default:
		$.messager.alert('提示', '您选择了多条记录数，请每次修改一条记录', 'warning');
		break;
	}
}

function saveRow() {
	_datasDatagrid.datagrid('endEdit', editRowsNumber);
}

function rejectRow() {
	editRowsNumber = -1;
	_datasDatagrid.datagrid('rejectChanges');
	_datasDatagrid.datagrid('unselectAll');
}

function search_datas() {
	var formData = selectForm.form('getData', true);
	if(formData.createDate1 != '' && formData.createDate2 != '' && formData.createDate1 > formData.createDate2){
		$.messager.alert('提示', '开始时间不得大于结束时间，请重新选择！', 'warning');
	} else {
		if (selectForm.form('validate')) {
			_datasDatagrid.datagrid('load',sy.serializeObject(selectForm));
		}
	}
};

function dialogHandler() {
	//if (formWeixinMsg.form('validate')) {
		var url = sy.bp() + "/admin/weixin/imageTextMsg/";
		if (id.val() == '0') {
			url += "add";
		} else {
			url += "update";
		}
		$.post(url, $('#formWeixinMsg').serialize(), function(data) {
			if (data && data.result == 1) {
				dialogWeixinMsg.dialog('close');
				_datasDatagrid.datagrid('reload');
				$.messager.show({title:'系统提示',msg:'提交成功!',timeout:2000,showType:'slide'});
			} else {
				$.messager.alert('系统提示', data.msg);
			}
		}, "json");
	//}
}

$(function(){
	parentCenterTabs = parent.centerTabs;
	_datasDatagrid = $('#_datasDatagrid');
	editRowsNumber = -1;
	selectForm = $('#selectForm');
	var jsonArr;
	//= [{value:0,text:'被动回复'},{value:1,text:'永久素材'}];
	dialogWeixinMsg = $('#dialogWeixinMsg').show().dialog({
		resizable : false,
		closed : true,
		closable : true,
		modal : true,
	});
	formWeixinMsg = $('#formWeixinMsg').form({});
	id = $('#id');
	$('.yesMaterial').hide();
	status = $('#status').combobox({required:true,editable:false,valueField:'code',textField:'name',url:sy.bp()+'/admin/dictionary/listDictionary?name=图文消息类型',
		onLoadSuccess : function(data) {
			console.info(JSON.stringify(data));
		    jsonArr = JSON.parse(JSON.stringify(data)); 
	},

		onChange:function(newValue, oldValue){
			if (!newValue) {
				$('.noMaterial').show();
				$('.yesMaterial').hide();
				$('#isMaterial').val('');
			} else {
				$('.noMaterial').hide();
				$('.yesMaterial').show();
				$('#isMaterial').val('yes');
			}
		}
	}).combobox('activeTextArrow').combobox('setValue', 0);
	title = $('#title').validatebox({required:true,validType:['maxLength[25]']});
	description = $('#description').validatebox({required:true,validType:['maxLength[100]']});
	logo = $('#logo');
	sessionID = $('#sessionID').val();
	logo.uploadify({
		method:'post',
		swf:sy.bp() + '/resources/uploadify/uploadify.swf',
		uploader:sy.bp() + '/admin/fileUpload/weixin',
		fileObjName:'file',
		auto:true,
		buttonText:'上传图片',
	    queueSizeLimit:1,
	    multi:false,
	    removeCompleted:true,
	    successTimeout:300,
	    fileSizeLimit:'10MB',
		fileTypeDesc:'Image Files',
		fileTypeExts:'*.gif; *.jpg; *.png;',
		formData:{'sessionID':sessionID,'type':'imageText'},
	    onUploadSuccess:function(file, data, response) {
	    	var resObj = $.parseJSON(data);
	        if (resObj.result == 1) {
	        	var src = sy.bp() + '/resources/upload/weixin/' + resObj.obj;
	        	$('#logoPic').attr('src', src);
	        	picUrl.val(src);
	        } else {
	        	$.messager.alert('警告', data.msg, 'warning');
	        }
	    }
	});
	picUrl = $('#picUrl').validatebox({required:true,validType:['url','maxLength[200]']});
	url = $('#url').validatebox({required:true,validType:['url','maxLength[200]']});
	author = $('#author').validatebox({required:true,validType:['unnormal','maxLength[25]']});
	digest = $('#digest').validatebox({required:true,validType:['maxLength[100]']});
	content = $('#content').validatebox({required:true,validType:['maxLength[200]']});
	content_source_url = $('#content_source_url').validatebox({required:true,validType:['url','maxLength[200]']});
	show_cover_pic = $('#show_cover_pic').combobox({required:true,editable:false,valueField:'value',textField:'text',
		data:[{value:0,text:'否'},{value:1,text:'是'}]
	}).combobox('activeTextArrow').combobox('setValue', 1);
	thumb_media_id = $('#thumb_media_id').combogrid({panelWidth:430,idField:'media_id',textField:'id',pagination:true,multiple:false,fitColumns:true,
		pageSize:10,pageList:[10,20,30,40,50],border:false,sortName:'id',sortOrder:'desc',view:sy.myview,emptyMsg:'没有查询到相关数据',
		url:sy.bp()+'/admin/weixin/material/list',queryParams:{type:'thumb',status:'yes'},
		columns:[[
		  {field:'id',hidden:true},
		  {field:'media',title:'缩略图',width:50,formatter:function(value, row) {
        	  if (value) {
        		  return '<img src="'+sy.bp()+'/resources/upload/weixin/'+row.media+'" class="imgMaterial">'
        	  }
          }},
          {field:'createTime',title:'上传时间',width:200},
          {field:'media_id',hidden:true}
        ]]  
	}).combogrid('activeTextArrow');
	
	_datasDatagrid.datagrid({
		url : sy.bp()+'/admin/weixin/imageTextMsg/list',
		fit : true,
		autoRowHeight : false,
		striped : true,
		rownumbers : true,
		pagination : true,
		singleSelect : false,
		fitColumns : true,
		pageSize : 10,
		pageList : [10,20,30,40,50],
		nowrap : true,
		border : false,
		idField : 'id',
		sortName : 'id',
		sortOrder : 'desc',
		view: sy.myview,
        emptyMsg: '没有查询到相关数据',
		toolbar: [
			{text:'增加',iconCls: 'icon-add',handler: addRow},'-',
			{text:'批量删除',iconCls: 'icon-remove',handler: deleteRow},'-',
			{text:'编辑',iconCls: 'icon-edit',handler: updateRow},'-',
			{text:'保存',iconCls: 'icon-save',handler: saveRow},'-',
			{text:'撤销',iconCls: 'icon-redo',handler: rejectRow},'-',
			{text:'刷新',iconCls: 'icon-reload',handler: function(){_datasDatagrid.datagrid('reload');}}
		],
		frozenColumns: [[
            {field:'id',title:'编号',align:'center',width:100,sortable:true,checkbox:true},
		]],
		columns:[[
          	{field:'status',title:'类型',align:'left',width:100,sortable:true,
            	formatter:function(value, row) {
            		for ( var i = 0; i < jsonArr.length; i++) {
						if (value == jsonArr[i].code) {
							return jsonArr[i].name;
						}
					}
            	}
	        },
          	{field:'title',title:'标题',align:'left',width:100,sortable:true},
          	{field:'description',title:'描述',align:'left',width:100,sortable:true},
          	{field:'picUrl',title:'图片链接',align:'left',width:100,sortable:true},
          	{field:'url',title:'图文链接',align:'left',width:100,sortable:true},
          	{field:'author',title:'作者',align:'left',width:100,sortable:true},
          	{field:'digest',title:'摘要',align:'left',width:100,sortable:true},
          	{field:'content',title:'内容',align:'left',width:100,sortable:true},
          	{field:'content_source_url',title:'原文链接',align:'left',width:100,sortable:true}
		]],
		onLoadSuccess : function(data) {
			editRowsNumber = -1;
			$.messager.progress('close');
		},
		onDblClickRow : function(rowIndex, rowData) {
			if (editRowsNumber != -1) {
				_datasDatagrid.datagrid('endEdit', editRowsNumber);
			} else {
				_datasDatagrid.datagrid('unselectAll').datagrid('selectRow', rowIndex);
				updateRow();
			}
		},
		onRowContextMenu : function(e, rowIndex, rowData){
			e.preventDefault();
			_datasDatagrid.datagrid('unselectAll').datagrid('selectRow', rowIndex);
			$('#datagridContextMenu').menu('show', {left:e.pageX,top:e.pageY});
		}
	});
});